#include "getroomlistresp.h"

GetRoomListResp::GetRoomListResp():ProtoSrvResp(PT_RESP_GET_ROOM_LIST)
{
    RoomManager::getInstance()->dump(_rooms_list);
}

bool GetRoomListResp::encode(ACE_OutputCDR &cdr)
{
    cdr << ACE_CDR::UShort(_rooms_list.size());
    if(_rooms_list.size()){
        RoomMap::iterator iter;
	for(iter = _rooms_list.begin(); iter != _rooms_list.end(); iter++){
	    std::string name = iter->first;

	    std::pair<quint8,bool> &attr = iter->second;
	    quint8 clients_cnt = attr.first;
	    bool   start = attr.second;

	    cdr << ACE_CDR::UShort(name.length());
	    cdr.write_char_array(name.data(),name.length());

	    cdr << ACE_CDR::UShort(clients_cnt);
	    cdr << ACE_OutputCDR::from_boolean(start);
	}
    }
    return true;
}

ProtoSrv* GetRoomListResp::decode(ACE_InputCDR &cdr)
{
    GetRoomListResp *resp = new GetRoomListResp;
    ACE_CDR::UShort room_cnt;
    cdr >> room_cnt;
    if(room_cnt > 0){
	for(int i = 0; i < room_cnt;i++){
	    ACE_CDR::UShort name_len;
	    cdr >> name_len;

	    char name[name_len + 1];
	    cdr.read_char_array(name,name_len);
	    name[name_len] = '\0';

	    ACE_CDR::UShort clients_cnt;
	    cdr >> clients_cnt;

	    bool start;
	    cdr >> ACE_InputCDR::to_boolean(start);

	    std::pair<quint8,bool>& attr = resp->_rooms_list[name];
	    attr.first = clients_cnt;
	    attr.second = start;
	}
    }

    return resp;
}

void GetRoomListResp::print()
{
    if(_rooms_list.size()){
        RoomMap::iterator iter;
	for(iter = _rooms_list.begin();iter != _rooms_list.end();iter++){
	    ACE_DEBUG((LM_DEBUG,"%s(%d:%d)\n",iter->first.data(),iter->second.first,iter->second.second));
	}
    }
    else
	ACE_DEBUG((LM_DEBUG,"Server Has No Room\n"));
}
